// 定义 Native 可以调用的回调函数类型
interface BridgeCallbacks {
  onLoginSuccess?: (data: any) => void;
  onShareSuccess?: (data: any) => void;
}

// 将回调函数挂载到 window 上，方便 Native 调用
const callbacks: BridgeCallbacks = {};
(window as any).bridgeCallbacks = callbacks;

// 封装 Promise 化的调用，让业务代码更优雅
function callNative<T>(action: string, data?: any): Promise<T> {
  return new Promise((resolve, reject) => {
    const callbackId = `cb_${Date.now()}_${Math.random()}`;
    
    // 注册一次性回调
    (callbacks as any)[callbackId] = (result: any) => {
      if (result.success) {
        resolve(result.data);
      } else {
        reject(result.error);
      }
      delete (callbacks as any)[callbackId]; // 用完即删
    };

    const message = {
      action,
      data,
      callbackId, // 把回调ID传给 Native
    };

    // --- 核心：适配不同环境的 JSBridge ---
    if ((window as any).android) { // 原生安卓
      (window as any).android.postMessage(JSON.stringify(message));
    } else if ((window as any).webkit?.messageHandlers?.myHandler) { // 原生iOS
      (window as any).webkit.messageHandlers.myHandler.postMessage(message);
    } else if ((window as any).ReactNativeWebView) { // React Native
      (window as any).ReactNativeWebView.postMessage(JSON.stringify(message));
    } else if ((window as any).MyFlutterChannel) { // Flutter
        (window as any).MyFlutterChannel.postMessage(JSON.stringify(message));
    } else {
      // 在非 App 环境下（如浏览器调试）可以做降级处理或提示
      console.warn('当前环境非 App WebView，无法调用 Native 方法');
      reject('Not in a WebView environment');
    }
  });
}

// 封装具体的业务方法
export const bridge = {
  /**
   * 请求原生登录
   * @param provider 'wechat' | 'qq' | 'douyin'
   */
  login(provider: string): Promise<{ token: string; userInfo: any }> {
    return callNative('login', { provider });
  },

  /**
   * 请求原生分享
   * @param options 分享内容
   */
  share(options: { title: string; url: string; description?: string }): Promise<void> {
    return callNative('share', options);
  },

  /**
   * 获取用户信息
   */
  getUserInfo(): Promise<{ name: string; avatar: string }> {
    return callNative('getUserInfo');
  }
};

// Native 端也需要相应地调整，接收 message 对象，处理完后根据 callbackId 调用回来：
// webView.evaluateJavascript(`window.bridgeCallbacks.${callbackId}({ success: true, data: ... })`);
